#include "console.h"
#include "general.h"
#include "mstring.h"
#include "assert.h"

#define PRINTF_PRECISION

/* printf long long */
#ifdef MXSETUP_CONSOLE_USE_LONGLONG
# define PRINTF_LONGLONG
#endif

#define ZEROPAD     (1 << 0)    /* pad with zero */
#define SIGN        (1 << 1)    /* unsigned/signed long */
#define PLUS        (1 << 2)    /* show plus */
#define SPACE       (1 << 3)    /* space if plus */
#define LEFT        (1 << 4)    /* left justified */
#define SPECIAL     (1 << 5)    /* 0x */
#define LARGE       (1 << 6)    /* use 'ABCDEF' instead of 'abcdef' */
#define ISDIGIT(c)  ((unsigned)((c) - '0') < 10)

/* the device for console */
volatile mx_device_pt condev = mx_null;
/* the buffer size for mx_vsnprintf */
volatile mx_usize_t bufsize = 0;

static inline int skip_atoi(const char **s)
{
    register int i = 0;
    while (ISDIGIT(**s))
    {
        i = i * 10 + *((*s)++) - '0';        
    }
    return i;
}

#ifdef PRINTF_LONGLONG
static inline int divide(long long *n, int base)
{
    int res = 0;

    /* optimized for processor which does not support divide instructions. */
    if (base == 10)
    {
        res = (int)(((unsigned long long)*n) % 10U);
        *n = (long long)(((unsigned long long)*n) / 10U);
    }
    else
    {
        res = (int)(((unsigned long long)*n) % 16U);
        *n = (long long)(((unsigned long long)*n) / 16U);
    }

    return res;
}
#else
static inline int divide(long *n, int base)
{
    int res = 0;

    /* optimized for processor which does not support divide instructions. */
    if (base == 10)
    {
        res = (int)(((unsigned long)*n) % 10U);
        *n = (long)(((unsigned long)*n) / 10U);
    }
    else
    {
        res = (int)(((unsigned long)*n) % 16U);
        *n = (long)(((unsigned long)*n) / 16U);
    }

    return res;
}
#endif

#ifdef PRINTF_PRECISION
static char *print_number(char *buf,
                          char *end,
#ifdef PRINTF_LONGLONG
                          long long  num,
#else
                          long  num,
#endif
                          int   base,
                          int   s,
                          int   precision,
                          int   type)
#else
static char *print_number(char *buf,
                          char *end,
#ifdef PRINTF_LONGLONG
                          long long  num,
#else
                          long  num,
#endif
                          int   base,
                          int   s,
                          int   type)
#endif
{
    char c = 0, sign = 0;
#ifdef PRINTF_LONGLONG
    char tmp[32] = {0};
#else
    char tmp[16] = {0};
#endif
    int precision_bak = precision;
    const char *digits = mx_null;
    static const char small_digits[] = "0123456789abcdef";
    static const char large_digits[] = "0123456789ABCDEF";
    register int i = 0;
    register int size = 0;

    size = s;

    digits = (type & LARGE) ? large_digits : small_digits;
    if (type & LEFT)
    {
        type &= ~ZEROPAD;        
    }

    c = (type & ZEROPAD) ? '0' : ' ';

    /* get sign */
    sign = 0;
    if (type & SIGN)
    {
        if (num < 0)
        {
            sign = '-';
            num = -num;
        }
        else if (type & PLUS)
        {
            sign = '+';            
        }
        else if (type & SPACE)
        {
            sign = ' ';            
        }
    }

#ifdef PRINTF_SPECIAL
    if (type & SPECIAL)
    {
        if (base == 16)
        {
            size -= 2;            
        }
        else if (base == 8)
        {
            size--;            
        }
    }
#endif

    i = 0;
    if (num == 0)
    {
        tmp[i++] = '0';        
    }
    else
    {
        while (num != 0)
        {
            tmp[i++] = digits[divide(&num, base)];            
        }
    }

#ifdef PRINTF_PRECISION
    if (i > precision)
    {
        precision = i;        
    }
    size -= precision;
#else
    size -= i;
#endif

    if (!(type & (ZEROPAD | LEFT)))
    {
        if ((sign) && (size > 0))
        {
            size--;            
        }

        while (size-- > 0)
        {
            if (buf < end)
            {
                *buf = ' ';               
            }

            ++ buf;
        }
    }

    if (sign)
    {
        if (buf < end)
        {
            *buf = sign;
        }
        -- size;
        ++ buf;
    }

#ifdef PRINTF_SPECIAL
    if (type & SPECIAL)
    {
        if (base == 8)
        {
            if (buf < end)
            {
                *buf = '0';                
            }

            ++ buf;
        }
        else if (base == 16)
        {
            if (buf < end)
            {
                *buf = '0';                
            }

            ++ buf;
            if (buf < end)
            {
                *buf = type & LARGE ? 'X' : 'x';
            }
            ++ buf;
        }
    }
#endif

    /* no align to the left */
    if (!(type & LEFT))
    {
        while (size-- > 0)
        {
            if (buf < end)
            {
                *buf = c;                
            }

            ++ buf;
        }
    }

#ifdef PRINTF_PRECISION
    while (i < precision--)
    {
        if (buf < end)
        {
            *buf = '0';            
        }

        ++ buf;
    }
#endif

    /* put number in the temporary buffer */
    while (i-- > 0 && (precision_bak != 0))
    {
        if (buf < end)
        {
            *buf = tmp[i];            
        }

        ++ buf;
    }

    while (size-- > 0)
    {
        if (buf < end)
        {
            *buf = ' ';            
        }

        ++ buf;
    }

    return buf;
}

/**
 * generate a string to the specified buffer by format string ("string %d", var)
 * @param buf: the buffer for output string
 * @param size: the buffer size, maximum write (size-1) and the (size) is '\0'
 * @param fmt: format string like ("string %d")
 * @param args: variable parameter (va_list) s(string)
 * @note: v(variadic arguments) n(number check)
 * @return: the number of characters actually written to the buffer (not contain '\0'),
 *          it can more then the buffer size so that need check
 */
mx_int32_t mx_vsnprintf (char* buf, mx_usize_t size, const char* fmt, va_list args)
{
#ifdef PRINTF_LONGLONG
    unsigned long long num = 0;
#else
    long num = 0;
#endif
    int i = 0, len = 0;
    char *str = mx_null, *end = mx_null, c = 0;
    const char *s = mx_null;

    mx_uint8_t base = 0;            /* the base of number */
    mx_uint8_t flags = 0;           /* flags to print number */
    mx_uint8_t qualifier = 0;       /* 'h', 'l', or 'L' for integer fields */
    mx_int32_t field_width = 0;     /* width of output field */

#ifdef PRINTF_PRECISION
    int precision = 0;      /* min. # of digits for integers and max for a string */
#endif

    str = buf;
    end = buf + size;

    /* Make sure end is always >= buf */
    if (end < buf)
    {
        end  = ((char *) - 1);
        size = end - buf;
    }

    for (; *fmt ; ++fmt)
    {
        if (*fmt != '%')
        {
            if (str < end)
            {
                *str = *fmt;                
            }

            ++ str;
            continue;
        }

        /* process flags */
        flags = 0;

        while (1)
        {
            /* skips the first '%' also */
            ++ fmt;
            if (*fmt == '-') flags |= LEFT;
            else if (*fmt == '+') flags |= PLUS;
            else if (*fmt == ' ') flags |= SPACE;
            else if (*fmt == '#') flags |= SPECIAL;
            else if (*fmt == '0') flags |= ZEROPAD;
            else break;
        }

        /* get field width */
        field_width = -1;
        if (ISDIGIT(*fmt))
        {
            field_width = skip_atoi(&fmt);            
        }
        else if (*fmt == '*')
        {
            ++ fmt;
            /* it's the next argument */
            field_width = va_arg(args, int);
            if (field_width < 0)
            {
                field_width = -field_width;
                flags |= LEFT;
            }
        }

#ifdef PRINTF_PRECISION
        /* get the precision */
        precision = -1;
        if (*fmt == '.')
        {
            ++ fmt;
            if (ISDIGIT(*fmt))
            {
                precision = skip_atoi(&fmt);                
            }
            else if (*fmt == '*')
            {
                ++ fmt;
                /* it's the next argument */
                precision = va_arg(args, int);
            }
            if (precision < 0)
            {
                precision = 0;
            }
        }
#endif
        /* get the conversion qualifier */
        qualifier = 0;
#ifdef PRINTF_LONGLONG
        if (*fmt == 'h' || *fmt == 'l' || *fmt == 'L')
#else
        if (*fmt == 'h' || *fmt == 'l')
#endif
        {
            qualifier = *fmt;
            ++ fmt;
#ifdef PRINTF_LONGLONG
            if (qualifier == 'l' && *fmt == 'l')
            {
                qualifier = 'L';
                ++ fmt;
            }
#endif
        }

        /* the default base */
        base = 10;

        switch (*fmt)
        {
        case 'c':
            if (!(flags & LEFT))
            {
                while (--field_width > 0)
                {
                    if (str < end) *str = ' ';
                    ++ str;
                }
            }

            /* get character */
            c = (mx_uint8_t)va_arg(args, int);
            if (str < end)
            {
                *str = c;
            }
            ++ str;

            /* put width */
            while (--field_width > 0)
            {
                if (str < end) *str = ' ';
                ++ str;
            }
            continue;

        case 's':
            s = va_arg(args, char *);
            if (!s)
            {
                s = "(mx_null)";
            }

            len = mx_strlen(s);
#ifdef PRINTF_PRECISION
            if (precision > 0 && len > precision)
            {
                len = precision;
            }
#endif

            if (!(flags & LEFT))
            {
                while (len < field_width--)
                {
                    if (str < end) *str = ' ';
                    ++ str;
                }
            }

            for (i = 0; i < len; ++i)
            {
                if (str < end) *str = *s;
                ++ str;
                ++ s;
            }

            while (len < field_width--)
            {
                if (str < end) *str = ' ';
                ++ str;
            }
            continue;

        case 'p':
            if (field_width == -1)
            {
                field_width = sizeof(void *) << 1;
                flags |= ZEROPAD;
            }
#ifdef PRINTF_PRECISION
            str = print_number(str, end,
                               (long)va_arg(args, void *),
                               16, field_width, precision, flags);
#else
            str = print_number(str, end,
                               (long)va_arg(args, void *),
                               16, field_width, flags);
#endif
            continue;

        case '%':
            if (str < end)
            {
                *str = '%';
            }
            ++ str;
            continue;

        /* integer number formats - set up the flags and "break" */
        case 'o':
            base = 8;
            break;

        case 'X':
            flags |= LARGE;
        case 'x':
            base = 16;
            break;

        case 'd':
        case 'i':
            flags |= SIGN;
        case 'u':
            break;

        default:
            if (str < end)
            {
                *str = '%';
            }
            ++ str;

            if (*fmt)
            {
                if (str < end)
                {
                    *str = *fmt;
                }
                ++ str;
            }
            else
            {
                -- fmt;
            }
            continue;
        }

#ifdef PRINTF_LONGLONG
        if (qualifier == 'L')
        {
            num = va_arg(args, long long);
        }
        else if (qualifier == 'l')
#else
        if (qualifier == 'l')
#endif
        {
            num = va_arg(args, long);
            if (flags & SIGN)
            {
                num = (mx_int32_t)num;
            }
        }
        else if (qualifier == 'h')
        {
            num = (mx_uint16_t)va_arg(args, mx_int32_t);
            if (flags & SIGN)
            {
                num = (mx_int16_t)num;
            }
        }
        else
        {
            num = va_arg(args, long);
            if (flags & SIGN)
            {
                num = (mx_int32_t)num;
            }
        }
#ifdef PRINTF_PRECISION
        str = print_number(str, end, num, base, field_width, precision, flags);
#else
        str = print_number(str, end, num, base, field_width, flags);
#endif
    }

    if (size > 0)
    {
        if (str < end)
        {
            *str = '\0';
        }
        else
        {
            end[-1] = '\0';
        }
    }

    /* the trailing XP_null byte doesn't count towards the total
    * ++str;
    */
    return str - buf;
}

/* string format */
void mx_sprintf (char* buf, mx_usize_t size, const char* fmt, ...)
{
    va_list args;
    va_start(args, fmt);
    mx_vsnprintf(buf, size, fmt, args);
    va_end(args);
}

/**
 * initialize console
 * @param devname: device name
 * @param obufsize: the output string buffer size
 * @return: void
 */
void console_init (char* devname, mx_usize_t obufsize)
{
    mx_device_pt dev = mx_device_get(devname);
    if (dev != mx_null)
    {
        mx_device_open(dev);
        condev = dev;
    }
    if (obufsize)
    {
        bufsize = obufsize;
    }
}

/**
 * get the device of console
 */
mx_device_pt console_device ()
{
    return condev;
}

/**
 * print a string to console
 * @param fmt: string format
 * @param ...: pattern variable
 * @return: void
 */
void console(const char *fmt, ...)
{
    va_list args;
    char outbuf[bufsize];   // index(bufsize-1) = '\0'
    mx_device_pt dev = condev;
    if (dev != mx_null)
    {
        va_start(args, fmt);
        /* generate format string, the (bufsize - 1) is for '\0' */
        mx_usize_t len = mx_vsnprintf(outbuf, bufsize, fmt, args);
        va_end(args);
        /* avoid overflow and cut '\0' */
        mx_usize_t vbufsize = bufsize - 1;
        if (len > vbufsize)
        {
            len = vbufsize;
        }
        mx_device_write(dev, outbuf, len);
    }
}

/**
 * print a string to console with new line
 * @param fmt: string format
 * @param ...: pattern variable
 * @return: void
 */
void consoleline (const char *fmt, ...)
{
    va_list args;
    char outbuf[bufsize + 1];   // index(bufsize-1) = '\0', it can be write to '\r'
    mx_device_pt dev = condev;
    if (dev != mx_null)
    {
        va_start(args, fmt);
        /* generate format string, the (bufsize - 1) is for '\0' */
        mx_usize_t len = mx_vsnprintf(outbuf, bufsize, fmt, args);
        va_end(args);
        /* avoid overflow and cut '\0' */
        mx_usize_t vbufsize = bufsize - 1;
        if (len > vbufsize)
        {
            len = vbufsize;
        }
        /* append line break */
#ifdef CONSOLE_NEWLINE_SPECIAL
        outbuf[len++] = '\r';
        outbuf[len++] = '\n';
#else
        outbuf[len++] = '\n';
#endif
        mx_device_write(dev, outbuf, len);
    }
}

/**
 * print a char to console
 * @param c: character
 * @return: void
 */
void console_putc (char c)
{
    if (condev != mx_null)
    {
        mx_device_write(condev, &c, 1);
    }
}

/**
 * print a string to console
 * @param s: string
 * @return: void
 */
void console_puts (mx_string_pt s)
{
    if (condev != mx_null)
    {
        mx_size_t len = mx_strlen(s);
        mx_device_write(condev, s, len);
    }
}
